package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func Viper() *viper.Viper {
	v := viper.New()
	v.SetConfigFile("config.yaml")
	v.SetConfigType("yaml")
	v.AddConfigPath(".")
	err := v.ReadInConfig()
	if err != nil {
		log.Println("Fatal error config file: ", err.Error())
	}
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		if err = v.Unmarshal(&NodeConfig); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(&NodeConfig); err != nil {
		fmt.Println(err)
	}
	return v
}

type System struct {
	UserName string `mapstructure:"username" json:"username" yaml:"username"`
	Password string `mapstructure:"password" json:"password" yaml:"password"`
	Sleep    int    `mapstructure:"sleep" json:"sleep" yaml:"sleep"`
}

type Tls struct {
	Enable   bool   `yaml:"enable"`
	CaFile   string `yaml:"ca-file"`
	CertFile string `yaml:"cert-file"`
	KeyFile  string `yaml:"key-file"`
}

type Server struct {
	System System `mapstructure:"system" json:"system" yaml:"system"`
	Tls    Tls    `yaml:"tls"`
}

var (
	NodeVp     *viper.Viper
	NodeConfig Server
)
